package com.weilive.api.gate.json.handler;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.UncategorizedSQLException;
import org.springframework.stereotype.Service;

import com.weilive.api.ServerErrors;
import com.weilive.api.gate.json.protocol.CSA_UpdateUserInfo;
import com.weilive.api.gate.json.protocol.CSQ_UpdateUserInfo;
import com.weilive.api.service.UserSystem;
import com.weilive.core.protocol.json.JsonRequest;
import com.weilive.core.protocol.json.JsonRequestHandler;
import com.weilive.core.protocol.json.JsonResponse;

@Service
public class CSQ_UpdateUserInfo_JsonHandler extends JsonRequestHandler {

	@Autowired
	private UserSystem userSystem;

	public Class<?> getRequestType() {
		return CSQ_UpdateUserInfo.class;
	}

	public Class<?> getResponseType() {
		return CSA_UpdateUserInfo.class;
	}

	public JsonResponse handleRequest(JsonRequest request) throws Exception {
		CSQ_UpdateUserInfo params = (CSQ_UpdateUserInfo) request.getData();

		CSA_UpdateUserInfo response = new CSA_UpdateUserInfo();

		if (!StringUtils.isBlank(params.getCheckUserAlias())) {
			userSystem.checkUserAlias(params.getCheckUserAlias());
			response.setUserAlias(params.getCheckUserAlias());
		} else {
			// 0:游客
			long userId = userSystem.getUserId(params.getSessionId());
			if (userId == 0) {
				return createErrorResponse(ServerErrors.USER_NOT_LOGIN);
			}
			if ((params.getUserAlias() == null && params.getUserProfile() == null && params.getUserPic() == null)) {
				return createErrorResponse(ServerErrors.PARAM_INVALID);
			}
			try {
				response = userSystem.setUserInfo(userId, params.getUserProfile(), params.getUserAlias(),
						params.getUserPic());
			} catch (UncategorizedSQLException e) {
				return createErrorResponse(ServerErrors.USER_NAME_OR_PROFILE_INVALID);
			}
		}

		return JsonResponse.create(response);
	}

}
